<?php
declare(strict_types=1);
namespace Traits;

trait DataTree
{
    /**
     * 生成树形结构
     * @param array $data
     * @param string $parentName
     * @return array
     */
    public function getTree(array $data,string $parentName = 'pid'): array
    {
        $items = [];
        foreach ($data as $v){
            $v['value'] = $v['id'];
            if (isset($v['permission_name'])) {
                $v['label'] = $v['permission_name'];
            }
            $items[$v['id']] = $v; // $items[1] =
        }
        $tree = array(); //格式化好的树
        foreach ($items as $item){
            if (isset($items[$item[$parentName]])){
                $items[$item[$parentName]]['children'][] = &$items[$item['id']];
            }else{
                $tree[] = &$items[$item['id']];
            }
        }
        return $tree;
    }

    /**
     * 生成树形结构
     * @param array $data
     * @param string $parentName
     * @param string $nodeName
     * @return array
     */
    public function tree(array $data,string $parentName = 'pid',string $nodeName='child'): array
    {
        $items = [];
        foreach ($data as $v){
            $items[$v['id']] = $v; // $items[1] =
        }
        $tree = array(); //格式化好的树
        foreach ($items as $item){
            if (isset($items[$item[$parentName]])){
                $items[$item[$parentName]][$nodeName][] = &$items[$item['id']];
            }else{
                $tree[] = &$items[$item['id']];
            }
        }
        return $tree;
    }
	
	 /**
     * 生成树形结构
     * @param array $data
     * @param string $parentName
     * @return array
     */
    public function getWechatTree(array $data,string $parentName = 'pid'): array
    {
        $items = [];
        foreach ($data as $v){
			if($v['type']=='view') {
				unset($v['appid']);
				unset($v['pagepath']);
			}
            $items[$v['id']] = $v; // $items[1] =
        }
        $tree = array(); //格式化好的树
        foreach ($items as $item){
            if (isset($items[$item[$parentName]])){
                $items[$item[$parentName]]['sub_button'][] = &$items[$item['id']];
            }else{
                $tree[] = &$items[$item['id']];
            }
        }
		foreach($tree as $key=>$vo) {
			unset($tree[$key]['id']);
			unset($tree[$key]['parent_id']);
			if(isset($vo['sub_button'])) {
				foreach($vo['sub_button'] as $kk=>$vv) {
					unset($tree[$key]['sub_button'][$kk]['id']);
					unset($tree[$key]['sub_button'][$kk]['parent_id']);
				}
			}
		}
        return ['button'=>$tree];
    }
}
